const fs = require('fs');
const path = require('path');

// ================== 配置区 ==================

// 要处理的文件列表（相对路径或绝对路径）
const filesToProcess = [
  './index.html',
  // 可以添加更多文件
  // './other.txt'
];

// 替换规则：[{ from: '旧字符串', to: '新字符串' }]
const replacements = [
  { from: 'A. A.', to: 'A.' },
  { from: 'A. B.', to: 'A.' },
  { from: 'A. C.', to: 'A.' },
  { from: 'A. D.', to: 'A.' },
  { from: 'B. A.', to: 'B.' },
  { from: 'B. B.', to: 'B.' },
  { from: 'B. C.', to: 'B.' },
  { from: 'B. D.', to: 'B.' },
  { from: 'C. A.', to: 'C.' },
  { from: 'C. B.', to: 'C.' },
  { from: 'C. C.', to: 'C.' },
  { from: 'C. D.', to: 'C.' },
  { from: 'D. A.', to: 'D.' },
  { from: 'D. B.', to: 'D.' },
  { from: 'D. C.', to: 'D.' },
  { from: 'D. D.', to: 'D.' },
  // 添加更多替换规则
];

// 日志文件路径
const logFile = './replace.log';

// 新文件命名规则：原文件名 + '.new'，放在 output_ 开头
const getNewFilePath = (originalPath) => {
  const dir = path.dirname(originalPath);
  const base = path.basename(originalPath);
  return path.join(dir, `output_${base}.new`);
};

// ================== 日志写入函数 ==================
function writeLog(message) {
  const timestamp = new Date().toISOString();
  const logMessage = `[${timestamp}] ${message}\n`;
  fs.appendFileSync(logFile, logMessage, 'utf8');
}

// ================== 主处理函数 ==================
function processFile(filePath) {
  let fileContent;
  try {
    fileContent = fs.readFileSync(filePath, 'utf8');
  } catch (err) {
    console.error(`❌ 无法读取文件: ${filePath}`, err.message);
    writeLog(`ERROR: 无法读取文件 ${filePath} - ${err.message}`);
    return;
  }

  const lines = fileContent.split(/\r?\n/); // 兼容 Windows 和 Unix 换行符
  const newLines = [];
  let totalReplacements = 0;

  lines.forEach((line, index) => {
    let modifiedLine = line;

    replacements.forEach(rule => {
      const regex = new RegExp(rule.from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'); // 转义特殊字符
      const matches = modifiedLine.match(regex);
      if (matches) {
        const count = matches.length;
        writeLog(
          `FILE: ${filePath} | LINE: ${index + 1} | REPLACED "${rule.from}" -> "${rule.to}" | COUNT: ${count}`
        );
        totalReplacements += count;
      }
      modifiedLine = modifiedLine.replace(regex, rule.to);
    });

    newLines.push(modifiedLine);
  });

  const newFilePath = getNewFilePath(filePath);
  try {
    fs.writeFileSync(newFilePath, newLines.join('\n'), 'utf8');
    console.log(`✅ 已生成新文件: ${newFilePath}`);
    writeLog(`SUCCESS: 文件 ${filePath} 处理完成，生成 ${newFilePath}，共替换 ${totalReplacements} 处`);
  } catch (err) {
    console.error(`❌ 写入新文件失败: ${newFilePath}`, err.message);
    writeLog(`ERROR: 写入新文件失败 ${newFilePath} - ${err.message}`);
  }
}

// ================== 执行入口 ==================
function main() {
  // 清空或初始化日志文件
  fs.writeFileSync(logFile, `[Replace Log Started at ${new Date().toISOString()}]\n`, 'utf8');

  console.log('🔍 开始处理文件...');
  filesToProcess.forEach(filePath => {
    if (fs.existsSync(filePath)) {
      console.log(`📄 处理文件: ${filePath}`);
      processFile(filePath);
    } else {
      console.warn(`⚠️ 文件不存在: ${filePath}`);
      writeLog(`WARNING: 文件不存在 ${filePath}`);
    }
  });
  console.log('🎉 所有文件处理完成！');
}

main();
